package com.kkd.kkdapp.activity;

import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.adapter.IndexListAdapter;
import com.kkd.kkdapp.adapter.IndexListAdapter.TimerHandler;
import com.kkd.kkdapp.db.app.model.KkdAppInfo;
import com.kkd.kkdapp.db.app.model.KkdExceptionDb;
import com.kkd.kkdapp.http.entity.AllConfig;
import com.kkd.kkdapp.http.entity.HomeTender;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.listener.OnSingleClickListener;
import com.kkd.kkdapp.utils.FileUtils;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.readystatesoftware.systembartint.SystemBarTintManager;

/**
 * 闪屏界面
 * 
 * @author mty
 * 
 */
public class SplashScreenActivity extends Activity {
	private Intent intent;

	protected SystemBarTintManager mTintManager;
	private ImageView splash_img;
	private Button ignore_bt;
	private AllConfig mAllConfig;
	private boolean isToUrl = false;
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 2:
				if (!isToUrl) {
					splash_img.clearAnimation();
					if (PreferenceUtils.getInstance().getwelcomeBoolean(
							SplashScreenActivity.this) == true) {
						intent = new Intent(SplashScreenActivity.this,
								HomeActivity.class);
						SplashScreenActivity.this.startActivity(intent);
						SplashScreenActivity.this.finish();
						overridePendingTransition(R.anim.home_in,
								R.anim.splash_out);
					} else {
						intent = new Intent(SplashScreenActivity.this,
								WelcomeActivity.class);
						SplashScreenActivity.this.startActivity(intent);
						SplashScreenActivity.this.finish();
					}
				}

				break;

			default:
				break;
			}

		}
	};

	/**
	 * 初始化为状态栏为纯黑色
	 */
	private void initTintManager() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			setTranslucentStatus(true);
		}

		mTintManager = new SystemBarTintManager(this);
		mTintManager.setStatusBarTintEnabled(true);
		mTintManager.setNavigationBarTintEnabled(true);
		mTintManager.setStatusBarTintResource(R.color.violet_543c9f);
	}

	@TargetApi(19)
	public void setTranslucentStatus(boolean on) {
		Window win = getWindow();
		WindowManager.LayoutParams winParams = win.getAttributes();
		final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
		if (on) {
			winParams.flags |= bits;
		} else {
			winParams.flags &= ~bits;
		}
		win.setAttributes(winParams);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initTintManager();
		KkdAppInfo appinfo = new KkdAppInfo();
		appinfo.backgroundTime = 0;
		KkdAppInfo.insert(appinfo);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		mAllConfig = PreferenceUtils.getInstance().getAllConfigData(this);
		long numForUpdateFalse = PreferenceUtils.getInstance()
				.getNumForUpdateFalse(this);
		if (numForUpdateFalse + 1 <= 1) {
			PreferenceUtils.getInstance().setNumForUpdateFalse(this,
					numForUpdateFalse + 1);
		} else {
			PreferenceUtils.getInstance().setNumForUpdateFalse(this, 1);
		}
		setContentView(R.layout.activity_splash_screen);
		ignore_bt = (Button) findViewById(R.id.ignore_bt);
		ignore_bt.setOnClickListener(new OnSingleClickListener() {

			@Override
			public void onSingleClick(View v) {
				Intent intent = new Intent(SplashScreenActivity.this,
						HomeActivity.class);
				SplashScreenActivity.this.startActivity(intent);
				SplashScreenActivity.this.finish();
				overridePendingTransition(R.anim.home_in, R.anim.splash_out);
			}
		});
		splash_img = (ImageView) findViewById(R.id.splash_img);
		splash_img.setOnClickListener(new OnSingleClickListener() {

			@Override
			public void onSingleClick(View v) {
				if (mAllConfig != null
						&& mAllConfig.getHomeIcon().getStart_up_limit() != null
						&& !TextUtils.isEmpty(mAllConfig.getHomeIcon()
								.getStart_up_limit().getToUrl())
						&& mAllConfig.getHomeIcon().getStart_up_limit()
								.getStatus() == 1) {
					shutCountdown();
					isToUrl = true;
					intent = new Intent(SplashScreenActivity.this,
							HomeActivity.class);
					intent.putExtra("gotoWhere", mAllConfig.getHomeIcon()
							.getStart_up_limit().getToUrl());
					startActivity(intent);
					SplashScreenActivity.this.finish();
				}
			}
		});
		String imgUrl = null;
		if (mAllConfig != null
				&& mAllConfig.getHomeIcon().getStart_up_limit() != null&& mAllConfig.getHomeIcon().getStart_up_limit().getStatus() == 1) {
			imgUrl = mAllConfig.getHomeIcon().getStart_up_limit()
					.getStartUpLimit();
		} else if (mAllConfig != null
				&& !TextUtils.isEmpty(mAllConfig.getHomeIcon().getStart_up())) {
			imgUrl = mAllConfig.getHomeIcon().getStart_up();

		}
		if (!TextUtils.isEmpty(imgUrl)) {

			ImageLoader.getInstance().displayGifImage(imgUrl, splash_img,
					new ImageLoadingListener() {

						@Override
						public void onLoadingStarted(String imageUri, View view) {

						}

						@Override
						public void onLoadingFailed(String imageUri, View view,
								FailReason failReason) {

							mHandler.sendEmptyMessage(2);

						}

						@Override
						public void onLoadingComplete(String imageUri,
								View view, Bitmap loadedImage) {
							if (imageUri.indexOf(".gif") >= 0) {
								if (mAllConfig.getHomeIcon()
										.getStart_up_limit().getIsPass() == 1)
									ignore_bt.setVisibility(View.VISIBLE);
								startCountdown();
							} else {
								ignore_bt.setVisibility(View.GONE);
								mHandler.sendEmptyMessageDelayed(2, 4000);
							}

						}

						@Override
						public void onLoadingCancelled(String imageUri,
								View view) {
							mHandler.sendEmptyMessage(2);
						}
					});
		} else {
			mHandler.sendEmptyMessageDelayed(2, 3000);
		}
		mTintManager.setTintColor(0x00000000);
		List<KkdExceptionDb> excs = KkdExceptionDb.getAllPathAndDel();
		if (excs != null && excs.size() > 0) {
			for (KkdExceptionDb exc : excs) {
				try {
					String exStr = FileUtils.readFile(exc.path);
					LogUtil.d("upload exception file path = ", exc.path);
					KkdHttpMagager.getInstance().uploadException(exStr,
							String.class, new HttpCallBack() {

								@Override
								public void onSuccess(int statusCode,
										Object responseBody) {

								}

								@Override
								public void onFailure(int statusCode,
										String desc) {

								}
							});
				} catch (Exception e) {
					// 忽略，上传失败就失败吧
				}
			}

		}
		getAllConfig();
	}

	/**
	 * getAllConfig:(这里用一句话描述这个方法的作用). <br/>
	 * 
	 * @author askzhao
	 */
	private void getAllConfig() {
		// TODO Auto-generated method stub
		KkdHttpMagager.getInstance().getAllConfig(AllConfig.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						mAllConfig = (AllConfig) responseBody;
						PreferenceUtils.getInstance().setAllConfigData(
								SplashScreenActivity.this,
								(AllConfig) responseBody);
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						// 获取失败就算了，无所谓~~~
					}
				});
	}

	public static final int PERIOD = 1000;
	public static final int RECORD_TIMER = 8112;
	public static final int RECORD_DONE = 8113;
	public static final int RECORD_ERROR = 8114;
	private boolean isRecoding = false;
	private Timer mTimer = null;
	private TimerTask mTimerTask = null;

	private void startCountdown() {
		if (mTimerTask == null) {
			mTimerTask = new RecordTimeTask();

		}
		if (mTimer == null) {
			mTimer = new Timer();

		}
		mTimer.schedule(mTimerTask, 0, PERIOD);
		isRecoding = true;

	}

	private void shutCountdown() {
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
		if (mTimerTask != null) {
			mTimerTask.cancel();
			mTimerTask = null;
		}
		isRecoding = false;

	}

	public TimerHandler mTimerHandler = new TimerHandler(this);

	public static class TimerHandler extends Handler {
		WeakReference<SplashScreenActivity> reference;
		private int time = 4;

		public TimerHandler(SplashScreenActivity intent) {
			reference = new WeakReference<SplashScreenActivity>(intent);
		}

		@Override
		public void dispatchMessage(Message msg) {
			switch (msg.what) {
			case RECORD_TIMER:
				time = time - 1;
				if (reference != null && reference.get() != null && time >= 0) {
					reference.get().ignore_bt.setText("跳过 " + time);
				} else {
					reference.get().shutCountdown();
					reference.get().mHandler.sendEmptyMessage(2);
				}
				break;
			case RECORD_DONE:
				if (reference != null && reference.get() != null) {
					reference.get().shutCountdown();
				}
				break;
			default:
				break;
			}
		}
	}

	private class RecordTimeTask extends TimerTask {
		@Override
		public void run() {
			if (isRecoding) {
				Message message = new Message();
				message.what = RECORD_TIMER;
				mTimerHandler.sendMessage(message);
			}

		}
	}

}
